package com.eskie.vmobileapp;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Vector;

import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.ViewDragHelper;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ExpandableListView.OnGroupClickListener;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

public class LoadActivity extends SherlockFragmentActivity {

	private DrawerLayout drawerLayout;
	private ExpandableListView drawerListView;
	private ActionBarDrawerToggle actionBarDrawerToggle;
	private PagerAdapter mPagerAdapter;
	private TextView titleTV;
	List<Fragment> fragments;
	ViewPager pager;
	Field mDragger;
	int edge;
	Field mEdgeSize;
	ViewDragHelper draggerObj;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_load);
		this.initialisePaging();
		
		//Changing the title of the action bar
	    LayoutInflater inflater = LayoutInflater.from(this);
	    View customView = inflater.inflate(R.layout.title_load, null);
	    titleTV = (TextView) customView.findViewById(R.id.title_load);
	    titleTV.setText("Load Code");
	    getSupportActionBar().setCustomView(customView);
	    getSupportActionBar().setDisplayShowCustomEnabled(true);

		// get ListView defined in activity_main.xml
		drawerListView = (ExpandableListView) findViewById(R.id.left_drawer);
		
		Drawer_List d = new Drawer_List("Load");

		// Set the adapter for the list view		
		final ExpandableDrawerAdapter expListAdapter = new ExpandableDrawerAdapter(
	                this, d.listDataHeader, d.listDataChild);
		drawerListView.setAdapter(expListAdapter);
		drawerListView.setGroupIndicator(null); 
		 		 
		// App Icon
		drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
		drawerLayout, /* DrawerLayout object */
		R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
		R.string.drawer_open, /* "open drawer" description */
		R.string.drawer_close /* "close drawer" description */
		);
		
		drawerTouch();

		// Set actionBarDrawerToggle as the DrawerListener
		drawerLayout.setDrawerListener(actionBarDrawerToggle);

		//Enabling the action bar
		getSupportActionBar().setDisplayShowTitleEnabled(false);
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setLogo(R.drawable.ic_drawer);		

		// just styling option add shadow the right edge of the drawer
		drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
		
		// When the user click the Generate ID
		drawerListView.setOnGroupClickListener(new OnGroupClickListener() {
			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				if (groupPosition==1){
					Toast.makeText(getApplicationContext(), "Feature not yet available", Toast.LENGTH_SHORT).show();
				}
				return false;
			}
		});
		
		drawerListView.setOnChildClickListener(new OnChildClickListener() {
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				menuItem(groupPosition, childPosition);
				return false;
			}
		});
	}
	
	/** This method makes the drawer can be open through swipe anywhere in the Fragment */
	private void drawerTouch(){
		try {
			mDragger = drawerLayout.getClass().getDeclaredField(
			        "mLeftDragger");
		} catch (NoSuchFieldException e) {}//mRightDragger for right obviously
		mDragger.setAccessible(true);
		
		try {
			draggerObj = (ViewDragHelper) mDragger
			        .get(drawerLayout);
		} catch (IllegalArgumentException e) {}
		catch (IllegalAccessException e) {}
		
		try {
			mEdgeSize = draggerObj.getClass().getDeclaredField(
			        "mEdgeSize");
		} catch (NoSuchFieldException e) {}
		mEdgeSize.setAccessible(true);
		
		try {
			edge = mEdgeSize.getInt(draggerObj);
		} catch (IllegalArgumentException e) {} catch (IllegalAccessException e) {}
		try {
			mEdgeSize.setInt(draggerObj, edge * 8);
		} catch (IllegalArgumentException e) {}
		catch (IllegalAccessException e) {}
	}

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		actionBarDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		actionBarDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId()==android.R.id.home) {
			if (drawerLayout.isDrawerOpen(drawerListView)){
	            drawerLayout.closeDrawer(drawerListView);
	        } else {
	            drawerLayout.openDrawer(drawerListView);
	        }
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	/** Creating Fragments */
	private void initialisePaging() {
		fragments = new Vector<Fragment>();
		fragments.add(Fragment.instantiate(this, ProductCodeActivity.class.getName()));
		fragments.add(Fragment.instantiate(this, ProductOTAActivity.class.getName()));
		this.mPagerAdapter = new PagerAdapter(
				super.getSupportFragmentManager(), fragments);
		pager = (ViewPager) super.findViewById(R.id.viewpager);
		pager.setAdapter(this.mPagerAdapter);
		
		pager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int arg0) {
				if (arg0==0){
					drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
					titleTV.setText("Load Code");
				}
				else{
					drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
					titleTV.setText("Load OTA");
				}
			}
			
			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {}
			
			@Override
			public void onPageScrollStateChanged(int arg0) {}
		});
	}

	private void menuItem(int groupPos, int childPos){
		if (groupPos==0 && childPos==0){
			new CustomDialog(this, CustomDialog.IDNumber).start();
		}
		else if (groupPos==0 && childPos==1){
			new CustomDialog(this, CustomDialog.Gateway).start();
		}
	}
}
